package com.guxiuwei.sys.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guxiuwei.sys.common.Result;
import com.guxiuwei.sys.entity.User;
import com.guxiuwei.sys.mapper.UserMapper;
import com.guxiuwei.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 谷秀伟
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //接收前端登录界面传入的用户手机号与密码，并与数据科中人员信息表进行判断，
    // 结果为真则进入主界面，不为真则返回错误提示：“手机号码或密码错误”
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        return userService.login(user);
    }

    @PostMapping("/logout")
    public Result<?> logout(){
        return userService.logout();
    }


    @GetMapping("/resetPwd")
    public Result<?> resetPwd(@RequestParam String uidStr,
                              @RequestParam String password,
                              @RequestParam String newPass){
        Long uid = Long.parseLong(uidStr);

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodeNewPassword = passwordEncoder.encode(newPass);
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.like(User::getUid,uid);
        User user = userMapper.selectOne(wrapper);

        if (passwordEncoder.matches(password,user.getPassword())){
            user.setPassword(encodeNewPassword);
            userMapper.updateById(user);
            return Result.success(user);
        }else {
            return new Result("0","原密码不正确");
        }
    }

    //获取前端传入的默认显示页码，页面容量数，
    // 和搜索框查询条件，对数据库中用户信息表进行分页查询
    @GetMapping("/selectAll")
    @PreAuthorize("hasAuthority('人事部')")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String search ){
        System.out.println(pageNum+"=="+pageSize+"=="+search);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("uid");
        if (StrUtil.isNotBlank(search)){
            wrapper.like("name",search);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize),wrapper );
        System.out.println(userPage);
        return Result.success(userPage);
    }

    //将user对象存入数据库中，并判断用户是否已经存在，设置新用户默认密码为123456
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('人事部')")
    public Result<?> save(@RequestBody User user){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getIdnum, user.getIdnum()));
        if (res != null){
            return Result.error("0","该用户已注册");
        } else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            user.setPassword(passwordEncoder.encode("123456"));
//        System.out.println(user);
            userMapper.insert(user);
            return Result.success();
        }
    }

    //对前端传入的user对象进行修改更新操作
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('人事部')")
    public Result<?> update(@RequestBody User user){
        userMapper.updateById(user);
        return Result.success();
    }

    //对前端传入的user对象的uid进行相关记录删除操作
    @DeleteMapping("/delete/{uid}")
    @PreAuthorize("hasAuthority('人事部')")
    public Result<?> delete(@PathVariable Long uid){
        userMapper.deleteById(uid);
        return Result.success();
    }

}

